# coding: utf-8
from rest_framework import serializers

from main import models
from main.common.valid.regex import (RE_DOMAIN, RE_EMAIL, RE_ID_CARD,
                                     RE_MOBILEPHONE, RE_PASSWORD, RE_PHONE,
                                     RE_TELEPHONE)


def error_phone(phone):
    return False if RE_PHONE.match(phone) else True


def error_id_card(id_card):
    return False if RE_ID_CARD.match(id_card) else True


def error_telephone(telephone):
    return False if RE_TELEPHONE.match(telephone) else True


def error_mobilephone(mobilephone):
    return False if RE_MOBILEPHONE.match(mobilephone) else True


def error_domain(domain):
    return False if RE_DOMAIN.match(domain) else True


def error_email(email):
    return False if RE_EMAIL.match(email) else True


def error_password(password):
    return False if RE_PASSWORD.match(password) else True


def validate_phone(phone):
    '''
    '电话是否有误
    :param phone:
    :return:
    '''
    if error_phone(phone):
        raise serializers.ValidationError(u'请填写正确电话')


def validate_domain(domain):
    '''
    '是否正确的域名
    :param domain:
    :return:
    '''
    if error_domain(domain):
        raise serializers.ValidationError(u'请填写正确域名')


def validate_id_card(id_card):
    '''
    '身份证号是否有误
    :param id_card:
    :return:
    '''
    if error_id_card(id_card):
        raise serializers.ValidationError(u'请填写正确身份证')


def validate_telephone(telephone):
    '''
    '座机是否有误
    :param telephone:
    :return:
    '''
    if error_telephone(telephone):
        raise serializers.ValidationError(u'请填写正确座机')


def validate_mobilephone(mobilephone):
    '''
    '手机是否有误
    :param mobilephone:
    :return:
    '''
    if error_mobilephone(mobilephone):
        raise serializers.ValidationError(u'请填写正确手机')


def validate_password(password):
    '''
    '密码是否有误
    :param password:
    :return:
    '''
    if error_password(password):
        raise serializers.ValidationError(u'请填写正确密码')


def validate_email(email, field_name=''):
    '''
    '邮箱是否有误
    :param email:
    :return:
    '''
    if error_email(email):
        msg = '请填写正确邮箱'
        if field_name:
            msg = {field_name: msg}
        raise serializers.ValidationError(msg)


def validate_packages(package_codes):
    query_kwargs = {
        'code__in': package_codes,
    }
    _package_codes = set(models.Package.objects.filter(
        **query_kwargs
    ).values_list('code', flat=True))

    if set(package_codes).difference(_package_codes):
        raise serializers.ValidationError(u'请选择正确的套餐')
